package com.togo.algorithm.medium.link;

import com.togo.algorithm.common.ListNode;
import com.togo.algorithm.util.ArrayUtil;
import com.togo.algorithm.util.ListNodeUtil;

/**
 * @Author taiyn
 * @Description
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 *
 *  
 *
 * 示例 1：
 *
 *
 * 输入：head = [1,2,3,4,5], k = 2
 * 输出：[4,5,1,2,3]
 * 示例 2：
 *
 *
 * 输入：head = [0,1,2], k = 4
 * 输出：[2,0,1]
 *
 * @Date 上午9:33 2022/4/10
 **/
public class No61 {

    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || k < 0) return head;

        ListNode tmp = head;
        int size = 0;
        while(tmp != null) {
            size++;
            tmp = tmp.next;
        }

        k = k % size;
        if(k == 0) return head;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy;
        while(k > 0) {
            fast = fast.next;
            k--;
        }

        ListNode slow = dummy;
        while(fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }

        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = head;

        return newHead;
    }

    public static void main(String[] args) {

        int[] array = new int[]{1,2,3,4,5};
        ListNode listNode = ListNodeUtil.buildByArray(array);
        No61 no61 = new No61();
        ListNode node = no61.rotateRight(listNode, 2);
        ListNodeUtil.print(node);
    }
}
